<?php

namespace App\Http\Middleware;

use App\Exceptions\ServiceException;
use App\Exceptions\ServiceExceptionConstant;
use App\Http\Repositories\Redis\UserRedis;
use Closure;
use GenTux\Jwt\Exceptions\InvalidTokenException;
use GenTux\Jwt\Exceptions\NoTokenException;
use GenTux\Jwt\GetsJwtToken;
use Illuminate\Support\Facades\Log;

class UserAuth
{
    use GetsJwtToken;

    public function __construct()
    {
    }


    public function handle($request, Closure $next)
    {
        if (!$token = $this->getToken()) {
            throw new NoTokenException();
        }
        if (!$this->jwtToken()->validate()) {
            throw new InvalidTokenException();
        }
        $payLoad         = $this->jwtPayload();
        $request->userId = $payLoad['uid'];
        //验证同一账号只能登录一个设备，如h5不能同时两个浏览器登录，h5和app可以同时登录
        $type = request()->get('header_type','h5');
        if(in_array($type, ['android', 'ios'])){
            $checkRes =UserRedis::getRedisInstance()->checkLoginToken($payLoad['uid'],$token);
        }else{
            $checkRes =UserRedis::getRedisInstance()->checkLoginToken($payLoad['uid'],$token,2);
        }
        if($checkRes === false){
            throw new ServiceException(ServiceExceptionConstant::getErrorData('need_login'));
        }
        return $next($request);

    }


}
